package com.jhs.boot.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.jhs.boot.common.beans.Common;
import com.jhs.boot.common.enums.StatusEnum;
import com.jhs.boot.common.exception.BusinessException;
import com.jhs.boot.common.result.Result;
import com.jhs.boot.config.FeignClientFactory;
import com.jhs.boot.system.converter.SysNodesTrafficConverter;
import com.jhs.boot.system.mapper.SysRouteMapper;
import com.jhs.boot.system.model.entity.SysNodes;
import com.jhs.boot.system.model.entity.SysNodesDhcp;
import com.jhs.boot.system.model.entity.SysNodesTraffic;
import com.jhs.boot.system.model.entity.SysRoute;
import com.jhs.boot.system.model.vo.NodesThirdVO;
import com.jhs.boot.system.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @Classname ScheduleTaskServiceImpl
 * @Description TODO
 * @Date 2025/8/14 11:33
 * @Created by zxy
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ScheduleTaskServiceImpl implements ScheduleTaskService {

    private final RedisTemplate<String, Object> redisTemplate;
    private final SysNodesService sysNodesService;
    private final SysNodesTrafficService sysNodesTrafficService;
    private final SysNodesTrafficConverter nodesTrafficConverter;
    private final SysNodesDhcpService sysNodesDhcpService;
    private final FeignClientFactory feignClientFactory;
    private final StringRedisTemplate redisTemplateStr;
    @Override
//    @Log( value = "MPP",module = LogModuleEnum.NODE_HEART)
    public void heartMpp() {
        deviceStatusIpdate(Common.ZERO);
    }

    /**
     * 根据类型监测设备上下线
     * @param type
     */
    private void deviceStatusIpdate(Integer type) {
        //查询redis  ap-0-*的所有设备
        List<SysNodes> list;
        List<Object> objects = redisTemplate.opsForValue().multiGet(redisTemplateStr.keys(Common.STATUS + type + "*"));
        if (CollectionUtils.isEmpty(objects)){
            list = sysNodesService.list(new LambdaQueryWrapper<SysNodes>().eq(SysNodes::getType,type));
            if (CollectionUtils.isEmpty(list)){
                log.error("设备表MPP类型为空");
            }else{
                //将库里面的数据存到redis  可以对旧数据进行处理
                sysNodesService.loadDateToRedis(list);
            }
        }else{
            try {
                list=objects.stream().map(obj ->   JSON.parseObject((String) obj,SysNodes.class)  ).collect(Collectors.toList());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            list.stream().forEach((one)->{
                if (!Common.nodeQueue.containsKey(one.getIp())){
                    log.info("设备 {}需要 上线通知",one.getIp());
                    processReqNodeUp(one);
                    return;
                }
                //若禁止上线则无法上线
                if(one.getPromise()== StatusEnum.ENABLE.getValue()){ return;}
                Result<NodesThirdVO>  nodesThirdVOResult = null;
                try {
                    FeignService feignService = feignClientFactory.getFeignClient(pingUrl( getRouteByRedis(one.getIp())));
                    log.info("三方接口存在3 {} ",one.getIp());
                    if (ObjectUtils.isNull(feignService)){
                        throw new BusinessException("接口服务掉线");
                    }
                    switch (type){
                        case 0:
                            nodesThirdVOResult = feignService.heartMpp(one.getIp(), type);
                            break;
                        case 1:
                            nodesThirdVOResult = feignService.heartMap(one.getIp(), type);
                            break;
                    }
                    log.error("请求 类型 {} 获取 {}",type,nodesThirdVOResult);
                    if (ObjectUtils.isNull(nodesThirdVOResult)){
                        throw new BusinessException("接口服务w掉线 {}",one);
                    }
                } catch (Exception e) {
                    if (reqDeviceReeor(one, e)) return;
                }
                if (ObjectUtils.isNotNull(nodesThirdVOResult)&& nodesThirdVOResult.getCode().equals(Common.RES_TRUE_STR) ){
                    if (ObjectUtils.isNotNull(nodesThirdVOResult.getData())){
                        NodesThirdVO nodesBean = nodesThirdVOResult.getData();
                        if (one.getStatus()==Common.ZERO ){
                            //未上线  则通知上线
                            //设备状态更新处理 （包含redis）
                            sysNodesService.upNoticeNodeAndRedisById(one,false,0);
                        }
                        if (ObjectUtils.isNotNull(nodesBean)){
                            SysNodesTraffic build = nodesTrafficConverter.nodesBeantoEntity(nodesBean);
                            build.setNodeId(one.getId());
                            build.setMem((nodesBean.getTotalMemory()-nodesBean.getFreeMemory())/nodesBean.getTotalMemory());
                            build.setDownVal(nodesBean.getRxBytes());
                            build.setFreeMemory(nodesBean.getFreeMemory());
                            build.setTotalMemory(nodesBean.getTotalMemory());
                            build.setUpVal(nodesBean.getTxBytes());
                            build.setTotalVal(nodesBean.getTxBytes()+nodesBean.getRxBytes());
                            sysNodesTrafficService.save(build);
                        }
                    }
                }
//                else{
//                    //将设备的状态设置未下线
//                    sysNodesService.lambdaUpdate().set(SysNodes::getStatus,Common.ZERO)
//                            .set(SysNodes::getUpdateTime, LocalDateTime.now())
//                            .set(SysNodes::getColor, NodesColorEnum.find(Common.ZERO).getColor_no())
//                            .eq(SysNodes::getIp, one.getIp()).update();
//
//                    log.error(" 【获取不到MPP下的节点 下线全部节点 包含所有子节点 】");
//                    //主节点下的子节点都下线
//                    extracted(one);
//                }
            });
        }
    }

    private boolean reqDeviceReeor(SysNodes one, Exception e) {
        String oldKey = Common.STATUS + one.getType() + Common.HENG+ one.getIp() + Common.HENG +"*";
        if (!existsByPattern(oldKey)){
            //不存在redis
            log.error("redis中不存在{}设备的信息", one.getIp());
            return true;
        }else{
            //存在就更新 判断设备的状态是多少
            Set<String> redisKeyByPattern = getRedisKeyByPattern(oldKey);
            redisKeyByPattern.stream().forEach(oldKeyVal -> {
                String statusStr = oldKeyVal.substring(oldKeyVal.lastIndexOf("-") + 1);
                //设备是离线的 不需修改  设备是有线的 需要修改
                if (statusStr.equals(Common.ONE_STR)){
                    sysNodesService.upNoticeNodeAndRedisById(one,true,Common.ONE);
                    log.error("设备需要更新 {}", e);
                }
            });
        }
        return false;
    }

    /**
     * 检查是否存在匹配模式的key
     * @param pattern
     * @return 返回不存在和key不是空的
     */
    public boolean existsByPattern(String pattern) {
        Set<String> keys = redisTemplate.keys(pattern);
        return keys != null && !keys.isEmpty();
    }

    /**
     * 是否存在匹配模式的key
     * @param pattern
     * @return 返回模糊查询的key
     */
    public Set<String> getRedisKeyByPattern(String pattern) {
        Set<String> keys = redisTemplate.keys(pattern);
        if (keys != null && !keys.isEmpty()) {
            return keys;
        }
        return null;
    }
    /**
     * 拼url
     * @param sysRoute
     * @return
     */
    private static String pingUrl(SysRoute sysRoute) {
        if (ObjectUtils.isNull(sysRoute)){
            throw new IllegalStateException("外不接口URL是空");
        }
        return Common.HTTP + sysRoute.getRouteIp() + ":" + sysRoute.getPort();
    }

    /**
     * 根据IP获取Redis路由
     * @param ip
     * @return
     */
    private SysRoute getRouteByRedis(String ip) {
        SysRoute javaObject =null;
        if (!redisTemplateStr.hasKey(Common.ROUTE + ip)){
            log.error("请匹配路由和节点 {}",ip);
            return null;
        }
        String strRoute = redisTemplateStr.opsForValue().get(Common.ROUTE + ip);
        JSONObject jsonObject = JSON.parseObject(strRoute);
        //如果有说明数据库已经存在路由了
        javaObject = JSON.toJavaObject(jsonObject, SysRoute.class);
        return javaObject;
    }
    /**
     * 下线当前节点下  大于 节点Type类型1 的节点
     *
     * @param one
     */
    private void extracted(  SysNodes one) {
        log.error("{}的节点更新其下所有终端和RFID ",one.getIp());
//        sysNodesService.updayeNodeAndRedis(one);

    }
    @Override
//    @Log( value = "MAP",module = LogModuleEnum.NODE_HEART)
    public void heartMap() {
        deviceStatusIpdate(Common.ONE);
    }


    /**
     * 获取所有节点的终端和RFID
     */
    @Override
//    @Log( value = "终端",module = LogModuleEnum.NODE_HEART)
    public void heartTerminal() {
        List<SysNodes> list=null;
        //获取在线的mpp、map终端
        Set<String> keys = redisTemplateStr.keys(Common.STATUS +  "*");
        keys = keys.stream().filter(s -> {
            String[] split = s.split(Common.HENG);
            String type = split[1].trim();
            String statusStr = split[3].trim();
            return statusStr.equals( Common.ONE_STR)&& Integer.parseInt(type)<Common.TWO;
        }).collect(Collectors.toSet());
        List<Object> objects = redisTemplate.opsForValue().multiGet(keys);
        //  处理当没有主节点在线时候
        if (CollectionUtils.isEmpty(objects)){
            list = sysNodesService.list(new LambdaQueryWrapper<SysNodes>().gt(SysNodes::getType,Common.TWO));
            if (CollectionUtils.isEmpty(list)){
                log.error("设备主节点类型为空  {} ",list.size());
//                sysNodesService.deviceUpdate(null,keysChild ,Common.ONE);
            }else{
                log.error("主节点在Redis中暂无，请等候主节点自动新增信息。。。。。");
            }
        }else{
            try {
                list=objects.stream().map(obj ->   JSON.parseObject((String) obj,SysNodes.class)  ).collect(Collectors.toList());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            //处理主节点存在redis中的终端
            list.stream().forEach(sysNodes -> {
                if(sysNodes.getPromise()== StatusEnum.ENABLE.getValue()){ return;}
                if (!Common.nodeQueue.containsKey(sysNodes.getIp())){
                    log.info("节点不包含在上先请求中   {}  ，请先进行上线请求 ", sysNodes.getIp());
                    processReqNodeUp(sysNodes);
                    return;
                }
                //查询节点下的终端
                Result<List<NodesThirdVO>>  infoTernimal = null;
                try {
                    SysRoute routeByRedis = getRouteByRedis(sysNodes.getIp());
                    if (ObjectUtils.isNull(routeByRedis)){
                        log.info("没有三方接口 {}",sysNodes.getIp());
                        return;
                    }
                    FeignService feignService = feignClientFactory.getFeignClient(pingUrl( routeByRedis));
                    if (ObjectUtils.isNull(feignService)){
                        throw new BusinessException("接口服务掉线"+sysNodes.getIp());
                    }
                    infoTernimal = feignService.getInfoTernimal(sysNodes.getIp(),sysNodes.getType());
                    log.info("终端信息 {}  {}",sysNodes.getIp(),infoTernimal);
                } catch (Exception e) {
                    log.error("主动请求节点下的终端和RFID出错 {} {} {}",sysNodes.getIp(),sysNodes.getType(),e);
                    return;
                }
                if ( ObjectUtils.isNotNull(infoTernimal)&&infoTernimal.getCode().equals(Common.RES_TRUE_STR)){
                    List<NodesThirdVO> nodesBean = infoTernimal.getData();
                    if (CollectionUtils.isEmpty(nodesBean)){
                        //如果是空  更新所有的子节点是下线状态
                        sysNodesService.updateTerminalNode(null,sysNodes,Common.ONE);
                    }else{
                        Map<String, String> keyHashMap = new HashMap<>();
                        nodesBean.stream().forEach(nodesThirdVO -> {
                            //  查询redis中该节点的终端信息  t-0-192.168.16.1-mac/rfid-1
                            String nextIp  = nodesThirdVO.getType() == Common.ZERO ? nodesThirdVO.getMac() : nodesThirdVO.getRfid();
                            String nodeIp = Common.NEXTNODE+ sysNodes.getType() + Common.HENG
                                    + sysNodes.getIp()+ Common.HENG + nextIp
                                    + "*" ;
                            Set<String> keys1 = redisTemplate.keys(nodeIp);
                            if (keys1.isEmpty()){
                                //  如果不存在终端  且终端查询出来的不是空  则添加终端
                                //新增且存到redis
                                sysNodesService.saveTerminalNode(nodesThirdVO,sysNodes);
                            }
                            keys1.stream().forEach(s -> {
                                keyHashMap.put(nextIp ,s);
                                if (redisTemplate.hasKey(s)){
                                    //   判断终端状态为1  不是1  更新终端上线
                                    sysNodesService.updateTerminalNode(nodesThirdVO,sysNodes,Common.ONE);
                                }
                            });
                        });
                        if (CollectionUtils.isNotEmpty(nodesBean) && (!keyHashMap.isEmpty())){
                            String nodeIp = Common.NEXTNODE+ sysNodes.getType() + Common.HENG
                                    + sysNodes.getIp()+ Common.HENG + "*"+"-"+Common.ONE_STR ;
                            Set<String> keys2 = redisTemplate.keys(nodeIp);
                            //todo 更新其他状态是1的终端 除了key1
                            keys2.stream().filter(s -> {
                                String[] split = s.split(Common.HENG);
                                System.out.println(split[3]+"---------");
                                return !keyHashMap.containsKey(split[3]);
                            }).forEach(s -> {
                                sysNodesService.updateNodeTermial(null,sysNodes,s,Common.ZERO);
                            });

                        }
                    }

               /* if (CollectionUtils.isEmpty(nodesBean)){
                    log.info("终端信息{} 节点是空 ",sysNodes.getIp());
                    //todo 查询redis中节点的终端信息
                    //下线改节点下的所有终端
                    sysNodesService.deviceUpdate(null,keysChild ,Common.ONE);
//                    extracted(  sysNodes);
                    return;
                }else{
                    //todo 存储到数据库

                    //todo 存储到redis
                }
                List<String> collect = nodesBean.stream().filter(nodesThirdVO -> nodesThirdVO.getMac()!=null).map(NodesThirdVO::getMac).collect(Collectors.toList());
                List<String> rfidCollect = nodesBean.stream().filter(nodesThirdVO -> nodesThirdVO.getRfid()!=null).map(NodesThirdVO::getRfid).distinct().collect(Collectors.toList());
//                sysNodesService.lambdaUpdate().set(SysNodes::getStatus,Common.ZERO)
//                        .notIn(collect.size()>0,SysNodes::getMac,collect)
//                        .or().notIn(rfidCollect.size()>0,SysNodes::getUserCode,rfidCollect)
//                        .eq(SysNodes::getParentId,sysNodes.getId()) .update();
//                log.info("设置状态更新 id{} IP{} 除{} {}",sysNodes.getId(),sysNodes.getIp(),collect,rfidCollect);
                //  将在线的终端（type>1）节点 排除mac和RFID 把它置为下线

                sysNodesService.lambdaUpdate().set(SysNodes::getStatus,Common.ZERO)
                        .set(SysNodes::getColor,NodesColorEnum.find(Common.ZERO).getColor_no())
                        .eq(SysNodes::getParentId,sysNodes.getId())
                        .gt(SysNodes::getType,Common.ONE).eq(SysNodes::getStatus,Common.ONE)
                        .notIn(collect.size()>0,SysNodes::getMac,collect)
                        .or().notIn(rfidCollect.size()>0,SysNodes::getUserCode,rfidCollect)
                        .update();
                sysNodesService.lambdaUpdate().set(SysNodes::getStatus,Common.ONE)
                        .set(SysNodes::getColor,NodesColorEnum.find(Common.TWO).getColor())
                        .eq(SysNodes::getParentId,sysNodes.getId())
                        .gt(SysNodes::getType,Common.ONE).eq(SysNodes::getStatus,Common.ZERO)
                        .in(collect.size()>0,SysNodes::getMac,collect)
                        .or().in(rfidCollect.size()>0,SysNodes::getUserCode,rfidCollect)
                        .update();

                nodesBean.stream().forEach(nodesThirdVO -> {
                    Long oneClient =null;
                    if (ObjectUtils.isNotNull(nodesThirdVO) ) {
                        //查询是否存在终端
                        log.info("观察设备的语句start");
                        oneClient = sysNodesService.count(new LambdaQueryWrapper<SysNodes>()
                                .eq(SysNodes::getParentId, sysNodes.getId())
                                .eq(nodesThirdVO.getMac()!=null,SysNodes::getMac, nodesThirdVO.getMac())
                                .eq(nodesThirdVO.getRfid()!=null,SysNodes::getUserCode, nodesThirdVO.getRfid())
                                .gt(SysNodes::getType,Common.ONE)//排除map
                        );
                        log.info("观察设备的语句end {} {}",oneClient);
                         if (isNullOrLessThanOne(oneClient)){
                            // 添加人员编号 RFID标签
                            SysNodes build = SysNodes.builder() .type(nodesThirdVO.getType() == Common.ZERO ? NodesColorEnum.END.getMode() : NodesColorEnum.RFID.getMode())
                                    .status(Common.ONE).color(NodesColorEnum.END.getColor()).userCode(nodesThirdVO.getRfid())
                                    .mac(nodesThirdVO.getMac()).deptId(sysNodes.getDeptId()).level(sysNodes.getType()+1)
                                    .symbolSize(nodesThirdVO.getType() == Common.ZERO ? NodesEnum.END.getVal() : NodesEnum.RFID.getVal()).promise(Common.ZERO)
                                    .parentId(sysNodes.getId())
                                    .build();
                            log.info("终端新增 {}", build);
                            sysNodesService.save(build);
                        }

                        else{
//                            if (oneClient.getType().intValue()>Common.ONE){
                                if (oneClient.getStatus().intValue()==Common.ZERO){
                                    oneClient.setStatus(Common.ONE);
                                    oneClient.setColor(NodesColorEnum.find(oneClient.getType()).getColor());
                                    oneClient.setCreateTime(LocalDateTime.now());
                                    log.info("终端更新 {}", oneClient);
                                    sysNodesService.updateById(oneClient);
                                }
//                            }
                        }
                    }
                });*/
                }
            });
        }

    }



    /**
     * 检查Long是否为null或小于1
     */
    public static boolean isNullOrLessThanOne(Long value) {
        return value == null || value < 1;
    }

    /**
     * 主动请求库中节点上线
     */
    @Override
    public void processReqNodeUp(SysNodes sysNodes) {
        if(ObjectUtils.isNull(sysNodes)){
            //获取mpp  map终端
            List<SysNodes> list = sysNodesService.list(new LambdaQueryWrapper<SysNodes>()
                    .lt(SysNodes::getType,  Common.TWO) );
            list.stream().forEach(sysNodes1 -> {
                reqNodeUP(sysNodes1);
            });
        }else{
            reqNodeUP(sysNodes);
        }
    }

    private void reqNodeUP(SysNodes sysNodes) {
        Result<List<NodesThirdVO>>  infoTernimal = null;
        try {
            SysRoute routeByRedis = getRouteByRedis(sysNodes.getIp());
            if (ObjectUtils.isNull(routeByRedis)){
                return;
            }
            FeignService feignService = feignClientFactory.getFeignClient(pingUrl(routeByRedis));
            log.info("三方接口存在1 {}  ", sysNodes.getIp());
            if (ObjectUtils.isNull(feignService)){
                throw new BusinessException("接口服务掉线");
            }
            infoTernimal = feignService.askOnline(sysNodes.getIp(), sysNodes.getType());
            log.info("请求节点上线是否成功 {}",infoTernimal);
            if (ObjectUtils.isNull(infoTernimal)){
                throw new BusinessException("接口服务掉线2");
            }
        } catch (Exception e) {
            //   跟新设备的状态
            reqDeviceReeor(sysNodes,e);
            log.error("主动请求节点上线出错 {}",e);
        }
    }

    @Override
    public void processDhcp() {
        //获取mpp
        List<SysNodes> list = sysNodesService.list(new LambdaQueryWrapper<SysNodes>()
                .lt(SysNodes::getType,  Common.ONE) );
        list.forEach(sysNodes -> {
            //查询MAP下的终端
            Result<List<NodesThirdVO>>  infoTernimal = null;
            try {
                SysRoute routeByRedis = getRouteByRedis(sysNodes.getIp());
                if (ObjectUtils.isNull(routeByRedis)){
                    log.info("没有三方接口 {}",sysNodes.getIp());
                    return;
                }
                FeignService feignService = feignClientFactory.getFeignClient(pingUrl(  routeByRedis));
                log.info("三方接口存在2 {} {}",sysNodes.getIp());
                if (ObjectUtils.isNull(feignService)){
                    throw new BusinessException("接口服务掉线");
                }
                infoTernimal = feignService.dhcpGet(sysNodes.getIp(),sysNodes.getType());
                log.info("获取DHCP表{}" ,infoTernimal);
            } catch (Exception e) {
                log.error("主动请求DHCP出错 {}",e);
            }
            if ( ObjectUtils.isNotNull(infoTernimal)&&infoTernimal.getCode().equals(Common.RES_TRUE_STR)&&ObjectUtils.isNotNull(infoTernimal.getData())) {
                List<NodesThirdVO> nodesBean = infoTernimal.getData();
                try {
                    nodesBean.stream().forEach(vo -> {
                        if (!redisTemplate.hasKey(vo.getMac())){
                            long count = sysNodesDhcpService.count(new LambdaQueryWrapper<SysNodesDhcp>().eq(SysNodesDhcp::getMac, vo.getMac()));
                            if (count<1){
                                sysNodesDhcpService.saveDhcp(vo);
                            }
                            redisTemplate.opsForSet().add(vo.getMac(),vo.getIp());
                        }
                    });
                } catch (Exception e) {
                    log.info("{}",e);
                }
            }
        });
    }
}
